
package kaizone.haining.chaobohui.activity;

import kaizone.haining.chaobohui.R;
import kaizone.haining.chaobohui.args.AppArgs;
import kaizone.haining.chaobohui.json.BannerDO;
import kaizone.haining.chaobohui.net.DataControl;
import kaizone.haining.chaobohui.util.Utils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class StartActiviy extends Activity implements DataControl.IDataUpdateListener {

    private int mNextingFlag = 0;

    private String mBannerDoUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.start_app);
        imageView.setScaleType(ScaleType.FIT_XY);

        setContentView(imageView);
        initAppArgs();

        // Handler handler = new Handler();
        // handler.postDelayed(new Runnable() {
        // @Override
        // public void run() {
        // next();
        // }
        // }, 1500);
        initBannerDo();
    }

    private void initBannerDo() {
        DataControl dataControl = new DataControl(this);
        dataControl.addChangeListener(this);
        mBannerDoUrl = BannerDO.URL + "&t=" + Utils.randomNum();
        dataControl.exec(mBannerDoUrl);
    }

    private void initAppArgs() {
        int startAppCount = AppArgs.readStartAppCount(this);
        startAppCount++;
        AppArgs.writeStartApp(this, startAppCount);
    }

    private void next() {
        if (mNextingFlag > 0)
            return;
        mNextingFlag++;
        int startAppCount = AppArgs.readStartAppCount(this);
        if (startAppCount > 1) {
            CBHActivity.come(this);
        } else {
            GuideActivity.come(this, 0);
        }
        finish();
    }

    @Override
    public Object backParse(String datastring, String requeststring) {
        if (TextUtils.isEmpty(datastring)) {
            return null;
        }
        if (TextUtils.isEmpty(requeststring)) {
            return null;
        }
        if (requeststring.equals(mBannerDoUrl)) {
            BannerDO bannerDO = BannerDO.parseJson(datastring);
            AppArgs.sBannerDO = bannerDO;
            return bannerDO;
        }//
        return null;
    }

    @Override
    public void foreUpdate(Object result, String requeststring) {
        next();
    }

    @Override
    public void exception(Exception e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(StartActiviy.this, "网络连接异常", 300).show();
            }
        });
        next();
    }

}
